package com.jiawa.train.member.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiawa.train.common.exception.BusinessException;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.member.domain.Member;
import com.jiawa.train.common.resp.CommonResp;
import com.jiawa.train.member.req.MemberRegisterReq;
import com.jiawa.train.member.service.serviceImpl.MemberService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @GetMapping("/list")
    public CommonResp<Page<Member>> list(@RequestParam(defaultValue = "1") int pageNum,
                                         @RequestParam(defaultValue = "10") int pageSize) {
        Page<Member> page = memberService.page(new Page<>(pageNum, pageSize));
        return new CommonResp<>(page);
    }

    @GetMapping("/{id}")
    public CommonResp<Member> get(@PathVariable Long id) {
        Member member = memberService.getById(id);
        return new CommonResp<>(member);
    }

    @PostMapping("/save")
    public CommonResp<Boolean> save(@RequestBody Member member) {
        boolean result = memberService.saveOrUpdate(member);
        return new CommonResp<>(result);
    }

    @DeleteMapping("/delete/{id}")
    public CommonResp<Boolean> delete(@PathVariable Long id) {
        boolean result = memberService.removeById(id);
        return new CommonResp<>(result);
    }

    @GetMapping("/count")
    public CommonResp<Long> count() {
        Long result = memberService.count();
        return new CommonResp<>(result);
    }

    @PostMapping("/register")
    public CommonResp<Long> register(@Valid @RequestBody MemberRegisterReq req) {
        // 检查手机号是否已注册
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", req.getMobile());
        Member existMember = memberService.getOne(wrapper);
        if (existMember != null) {
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_EXIST);
        }

        // 新建并保存
        Member member = new Member();
        member.setMobile(req.getMobile());
        memberService.save(member);
        return new CommonResp<>(member.getId());
    }
}
